package com.example.demo;

import com.example.demo.User;
import com.example.demo.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 查询所有用户
    @GetMapping
    public List<User> listUsers() {
        return userService.listUsers();
    }

    // 根据 id 查询用户
    @GetMapping("/{id}")
    public User getUser(@PathVariable("id") Integer id) {
        return userService.getUserById(id);
    }

    // 新增用户
    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }

    // 修改用户
    @PutMapping("/{id}")
    public User updateUser(@PathVariable("id") Integer id,
                           @RequestBody User user) {
        return userService.updateUser(id, user);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable("id") Integer id) {
        boolean ok = userService.deleteUser(id);
        if (ok) {
            return "删除成功";
        } else {
            return "未找到该用户";
        }
    }
}
